﻿/*globals _comma_separated_list_of_variables_*/
//## LEAGAL
/*
#region - Legal -

Copyright © 2011, Tateeda Media Network
All rights reserved. http://tateeda.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the Tateeda Media Network, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

#endregion - Legal -

*/
//#end
var currentVisit;
var appUserRetry = 0;
var siteSubjectsRetry = 0;
var maxRetry = 3;

$(document).ready(function () {
    GetSiteSubjects();
    GetSiteAppUsers();
    Init();
});

function Init() {
    var myArgs = window.dialogArguments;
    if (myArgs != null) {
        $("#start").val(myArgs[0]);
        $("#end").val(myArgs[1]);
        $("#allDay").val(myArgs[2]);
    }

    $("#Subject").change(function () {
        GetVisitsForSubject($("#Subject option:selected").val());
    });
    $("#formCopyBox").hide();
    $("#Visit").change(function () {
        RollFormCopyBox($("#Visit option:selected").text());
    });

    $("#Subject").hide();
    $("#Visit").hide();
    $('#AppUser').hide();
}

function GetSiteSubjects() {
    if (siteSubjectsRetry < maxRetry) {
        $.ajax({
            type: "POST",
            url: "/Scheduler/GetCalendarSiteSubjects",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadSubjects(data);
            },
            error: function () {
                GetSiteSubjects();
            }
        });

        siteSubjectsRetry++;
    } else {
        DisableSave();
    }
}

function GetSiteAppUsers() {
    if (appUserRetry < maxRetry) {
        $.ajax({
            type: "POST",
            url: "/Scheduler/GetSiteAppUsers",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadAppUsers(data);
            },
            error: function () {
                GetSiteAppUsers();
            }
        });
        appUserRetry++;
    } else {
        DisableSave();
    }
}

function DisableSave() {
    $("#save").attr('disabled', 'disabled');
}

function SaveVisit() {
    var title = $("#title").val();
    var subject = $("#Subject option:selected").val();
    var appUser = $("#AppUser option:selected").val();
    if (title.length > 0 && subject.length > 0 && appUser.length > 0) {
        var vReturnValue = new Object();
        vReturnValue.start = $("#start").val();
        vReturnValue.end = $("#end").val();
        vReturnValue.title = $("#title").val();
        vReturnValue.allDay = $("#start").val() == $("#end").val();
        vReturnValue.description = $("#description").val();
        vReturnValue.Subject = $("#Subject option:selected").val();
        vReturnValue.AppUser = $("#AppUser option:selected").val();
        vReturnValue.Visit = $("#Visit option:selected").val();
        window.returnValue = vReturnValue;
        window.close();
    } else {
        if (title.length == 0)
            $("#title").css('background-color', 'yellow');
        if (!subject)
            alert("Subject is missing!");
        if (!appUser)
            alert("Interviewer is missing!");
    }
}

function Cancel() {
    window.returnValue = null;
    window.close();
}

function LoadSubjects(result) {
    $('#Subject')
        .find('option')
        .remove()
        .end()
        .append('<option value="0">--Select--</option>')
        .val('0');

    if (result == null || result == undefined) { GetSiteSubjects(); return; }
    if (result != null) {
        $.each(result, function () {
            $('#Subject').append($("<option></option>").attr("value", this.SubjectId).text(this.SubjectId + " " + this.FirstName + " " + this.LastName));
        });
    } else {
        $('#Subject').html('There is an error. Please reload this form!');
    }

    $('#Subject').show();
}

function LoadAppUsers(result) {
    $('#AppUser')
        .find('option')
        .remove()
        .end()
        .append('<option value="0">--Select--</option>')
        .val('0');

    if (result == null || result == undefined) { GetSiteAppUsers(); return; }

    if (result != null) {
        $.each(result, function () {
            $('#AppUser').append($("<option></option>").attr("value", this.AppUserId).text(this.FirstName + " " + this.LastName));
        });
    } else {
        $('#AppUser').html('There is an error. Please reload this form!');
    }
    $('#AppUser').show();
}

function GetVisitsForSubject(subjectId) {
    $.ajax({
        type: "POST",
        url: "/Scheduler/LoadAvailableVisitsForSubject",
        data: "{'subjectId':'" + subjectId + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            FillVisitsForSubject(data);
        },
        error: function (e) {
            alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
        }
    });
}

function RollFormCopyBox(visit) {
    switch (visit) {
        case 'O0':
        case 'M24/Termination':
        case 'S0 (V)':
        case 'O0 (V)':
        case 'M24 (V)':
            $("#formCopyBox").show();
            break;
        default:
            $("#formCopyBox").hide();
            break;
    }
}

function SaveSchedule(ev) {
    if (ev == currentVisit) {
        if (ev.text != "New event") {
            return;
        }
    }

    var start = (ev.start_date.getMonth() + 1) + "/" + ev.start_date.getDate() + "/" + ev.start_date.getFullYear() + " " + ev.start_date.getHours() + ":" + ev.start_date.getMinutes() + ":00";
    var end = (ev.end_date.getMonth() + 1) + "/" + ev.end_date.getDate() + "/" + ev.end_date.getFullYear() + " " + ev.end_date.getHours() + ":" + ev.end_date.getMinutes() + ":00";
    var copyOldForms = ev.cbCopyForms;
    if (copyOldForms == undefined) copyOldForms = false;

    if (ev.Subject && ($(ev.Visit).val() || ev.Visit) && ev.AppUser) {
        $.ajax({
            type: "POST",
            url: "../../Services/ScheduleService.asmx/SaveAppointment",
            data: "{'appointmentId':'" + ev.id + "','subjectId':'" + ev.Subject + "','appUserId':'" + ev.AppUser + "','visitId':'" + ($(ev.Visit).val() | ev.Visit) + "','title':'" + ev.text + "', 'description':'" + ev.details + "', 'startTime':'" + start + "','endTime':'" + end + "','copyOldForms':'" + copyOldForms + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (appt) {
                VisitCreatedSuccess(ev, appt);
            },
            error: function (e) {
                alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
            }
        });
    }

    $("#Subject").val('');
}

function VisitCreatedSuccess(ev, appt) {
    var start = (ev.start_date.getMonth() + 1) + "/" + ev.start_date.getDate() + "/" + ev.start_date.getFullYear() + " " + ev.start_date.getHours() + ":" + ev.start_date.getMinutes() + ":00";

    ev.id = appt.d;
    alert('Appointment saved!');
    ReloadScheduler(new Date(start));
}

function DeleteSchedule(ev) {
    var appointmentId = ev.id;
    $.ajax({
        type: "POST",
        url: "../../Services/ScheduleService.asmx/DeleteVisit",
        data: "{'appointmentId':'" + appointmentId + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            alert('Visit deleted');
        },
        error: function () {
            alert("The DELETE statement conflicted with the REFERENCES and can not be deleted! There are some forms associated with this visit.");
        }
    });
}

function EditSchedule(ev) {
    // alert("id: " + ev.id + "  " + ev.text + " tiem: " + ev.start_date + " end: " + ev.end_date);
    var date = new Date();
    ev.details = "Updated by user on:" + date;
    SaveSchedule(ev);
}

function FillVisitsForSubject(result) {
    var select = $("#Visit");
    $(select)
        .find('option')
        .remove()
        .end()
        .append('<option value="0">--Select--</option>')
        .val('0');

    if (result == null || result == undefined) return;

    $.each(result, function () {
        $(select).append($("<option></option>").attr("value", this.VisitId).text(this.Name));
    });

    $(select).show();
}

function ReloadScheduler() {
    var dateFrom = new Date();
    dateFrom.setDate(dateFrom.getDate() - 90);
    var dateTo = new Date();
    dateTo.setDate(dateTo.getDate() + 270);
}